package com.erp.erp_mask.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.erp.erp_mask.mapper.TPartwareMapper;
import com.erp.erp_mask.mapper.TPurchaseMapper;
import com.erp.erp_mask.pojo.TPartware;
import com.erp.erp_mask.pojo.TPurchase;
import com.erp.erp_mask.service.TPurchaseService;
import com.erp.erp_mask.vo.Result;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import net.sf.jasperreports.engine.JasperRunManager;
import org.apache.ibatis.io.Resources;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.sql.DataSource;
import java.io.InputStream;
import java.util.Objects;

@RestController
@RequestMapping("/pur")
public class TPurchaseController {

    @Resource
    private TPurchaseService tPurchaseService;
    @Resource
    private TPartwareMapper tPartwareMapper;
    @Resource
    private TPurchaseMapper tPurchaseMapper;

    @GetMapping("/purorder")
    public ModelAndView index() {
        return new ModelAndView("/pur/purChase");
    }


    @GetMapping("/selectList")
    public Result searchList(String startdate, String overdate, String chasename, Long pageNo, Long pageSize) {
        return Result.success(tPurchaseService.searchlist(startdate,overdate,chasename,pageNo, pageSize));
    }

    @PostMapping("/add")
    public Result addList(@RequestBody TPurchase tPurchase) {
        System.out.println(tPurchase);
        try {
            tPartwareMapper.addlist(tPurchase);
            tPartwareMapper.stateedit(tPurchase.getChaseId());
            return Result.success("入库成功！");
        } catch (Exception e) {
            return Result.fail("入库失败！");
        }
    }

    @GetMapping("/selectname")
    public Result selectname(String name) {
        return Result.success(tPartwareMapper.selectname(name));
    }

    @PutMapping("/caiedit")
    public Result caiedit(@RequestBody TPurchase tPurchase) {
        try {
            tPartwareMapper.caiedit(tPurchase);
            tPartwareMapper.stateedit(tPurchase.getChaseId());
            return Result.success("入库成功!");
        } catch (Exception e) {
            return Result.fail("入库失败!");
        }
    }

    @Resource
    private DataSource dataSource;
    @SneakyThrows
    @GetMapping("/exportPdf")
    public void exportPdf( HttpServletResponse response){
        response.setContentType("application/pdf");
        InputStream in= Resources.getResourceAsStream("muban/cangku.jasper");
        JasperRunManager.runReportToPdfStream(in,response.getOutputStream(),null,dataSource.getConnection());
    }
}
